<?php
	session_start();
	require '../librarys/funcs/Manager.php';
	$p = $_GET["p"];

	if ($p == "login") {
		$username    = $_POST["username"];
		$password    = $_POST["password"];
		$remember_me = $_POST["remember_me"];
		if ($username != "" && $password != "" && $remember_me != "") {
			$manager = new Manager();
			$user    = $manager->get_user_by_username($username);
			if ($user == null) {
				echo "Tài khoản không tồn tại.";
			} else {
				$record_password = $user["password"];
				$password        = md5($password);
				if ($record_password != $password) {
					echo "Sai mật khẩu.";
				} else {
					if ($user['status'] == 1 && ($user['user_type'] == 1 || $user['user_type'] == 0)) {
						$_SESSION["is_login"]     = 1;
						$_SESSION["display_name"] = $user['firstname'] . ' ' . $user['lastname'];
						$_SESSION["user_id"]      = $user["id"];
						if ($user['user_type'] == 1) {
							$_SESSION["is_admin"] = 1;
						}
						if ($remember_me == "true") {
							$time = time();
							setcookie("remember", $remember_me, $time + 60 * 60 * 24 * 7);
							setcookie("username", $username, $time + 60 * 60 * 24 * 7);
							setcookie("password", $password, $time + 60 * 60 * 24 * 7);
						} else {
							$time = time();
							if (isset($_COOKIE["remember_me"])) setcookie("remember_me", $_COOKIE["remember_me"], time() - 3600);
							if (isset($_COOKIE["username"])) setcookie("username", $_COOKIE["username"], time() - 3600);
							if (isset($_COOKIE["password"])) setcookie("password", $_COOKIE["password"], time() - 3600);
						}
						echo 'success';
					} else {
						echo 'Tài khoản không có quyền truy cập.';
					}
				}
			}
		}
	}
?>